<template>
  <div class="mainor">
    <el-form
      :inline="true"
      :rules="rules"
      :model="monitorForm"
      class="demo-form-inline"
      ref="userListFrom"
      label-width="80px"
    >
      <div
        class="main_spac1 paddingBottom5"
      >
        <div class="main_white padding10 paddingBottom0">
          <div class="main_crumbs boxdq">
            <div class="main_crumbs_l">
              <a href="javascript:;" @click="$router.back(-1)">
                <i class="el-icon-arrow-down"></i>返回
              </a>
              <em>|</em>
              <span>库存调整</span>
            </div>
          </div>
          <div class="marginBottom5 marginTop15">
            <el-form-item
              label="调整类型"
              prop="form.type"
              class="marginBottom5"
              :rules="rules.type"
            >
              <el-select
                v-model.trim="monitorForm.form.type"
                placeholder="调整类型"
                class="wid240"
                ref="company"
              >
                <el-option
                  label="报损"
                  :value="parseInt(1)"
                ></el-option>
                <el-option
                  label="报溢"
                  :value="parseInt(2)"
                ></el-option>
              </el-select>
            </el-form-item>
            <div class="clearfix"></div>
            <el-form-item
              label="备注"
              prop="form.remark"
              class="marginRight0 marginTop10 remark_in"
            >
              <el-input
                v-model.trim="monitorForm.form.remark"
                placeholder="备注"
                clearable
              ></el-input>
            </el-form-item>
          </div>
        </div>
      </div>
      <!-- 商品名称 -->
      <div
        class="main_spac1"
        style="padding-top: 5px"
      >
        <div class="main_white padding10">
          <div class="mainor_sp boxdq" style="">
            <div class="box">
              <ul class="box">
                <li class="box">
                  <span> <em>*</em>商品名称： </span>
                  <el-autocomplete
                    v-model="formsp.value"
                    ref="searchSelect"
                    class="wid240 main_comm"
                    @clear="$refs.searchSelect.$children[0].blur()"
                    :fetch-suggestions="
                      (queryString, cb) => {
                        querySearchAsync(queryString, cb);
                      }
                    "
                    placeholder="商品名称/别名/编码/助记码"
                    clearable
                    :highlight-first-item="true"
                    value-key="name"
                    @select="
                      (item) => {
                        handleSelect(item);
                      }
                    "
                  >
                    <template slot-scope="{ item }">
                      <div class="main_name">
                        {{ item.goods.name }}【{{ item.spu_unit.title }}】
                      </div>
                    </template>
                  </el-autocomplete>
                </li>
                <li class="box">
                  <span> <em>*</em>数量： </span>
                  <el-input
                    v-model.trim="formsp.num"
                    ref="focusw2"
                    placeholder="数量"
                    clearable
                    class="wid140"
                    @keyup.enter.native="mainor_sp"
                  ></el-input>
                </li>
              </ul>
              <div class="marginBottom10">
                <el-button type="primary" @click="mainor_qr"
                  >确认(回车)</el-button
                >
                <el-button class="reset marginLeft5" type="info" @click="reset"
                  >重置</el-button
                >
              </div>
            </div>
          </div>
          <div class="main_table main_taf marginTop0" style="min-height: 330px">
            <el-table
              ref="multipleTable"
              :data="monitorForm.list"
              element-loading-text="加载中"
              fit
              border
              highlight-current-row
            >
            <el-table-column label="序号">
              <template slot-scope="scope">{{ scope.$index + 1 }}</template>
            </el-table-column>
              <el-table-column
                label="商品名称"
                prop="name"
                width="200"
                :show-overflow-tooltip="true"
              >
                  <template slot-scope="scope"
                    >{{ scope.row.name }}【{{
                      scope.row.spu_name
                    }}】</template
                  >
              </el-table-column>
              <el-table-column
                label="单位"
                prop="unit"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="实时库存"
                prop="inventory_num"
                width="120"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="调整数量"
                width="200"
                class-name="main_hei"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'list.' + scope.$index + '.num'"
                    :rules="rules.num"
                    label-width="10px"
                    label=" "
                  >
                    <el-input
                      v-model.trim="scope.row.num"
                      :ref="'num' + scope.row.goods_spu_id"
                      placeholder="调整数量"
                      class="wid110"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="库存价"
                prop="price"
              />
              <el-table-column
                label="调整金额"
                width="120"
              >
                <template slot-scope="scope">{{
                  parseFloat(scope.row.num) * parseFloat(scope.row.price)?(parseFloat(scope.row.num) * parseFloat(scope.row.price)).toFixed(2):0
                }}</template>
              </el-table-column>
              <el-table-column
                label="备注"
                prop="remark"
                width="350"
                class-name="main_hei"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model.trim="scope.row.remark"
                    placeholder="备注"
                    class="wid240"
                  ></el-input>
                  <el-link type="danger" @click="scdelete(scope.$index)"
                    >删除</el-link
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="newConBox_p200 paddingBottom10" id="newConBox">
            <div class="newConBox_h32">
              <div
                :class="['mainor_pr boxdq newConBox ', { on: searchBarFixed }]"
              >
                <div class="mainor_prl">
                  <el-button
                    type="primary"
                    @click="preservation"
                    v-repeatClick
                    >保存</el-button
                  >
                  <el-button @click="$router.back(-1)">取消</el-button>
                </div>
                <div class="mainor_prr">
                  <span>合计金额：¥{{ total }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
const shuju = {
  list: {
    name: "",
    goods_id: "",
    goods_spu_id: "",
    spu_name: "",
    unit: "",
    inventory_num: "",
    price: "",
    num: "",
    remark: "",
    show: false,
  },
  form: {
    type: 1,
    remark: "",
  },
  formsp: {
    name: [],
    girard: null,
    num: "",
    value: "",
  },
};

import {
  reportedSpills_add,
  reportedSpills_checkGoods
} from "@/api/warehouse/warehouseLoss";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import rules from "@/rules/warehouse/warehouseLoss_add";
import { goods_getGoodsSpu } from "@/api/currency";

export default {
  computed: {
    total() {
      let sz = 0;
      this.monitorForm.list.forEach((e) => {
        sz += parseFloat(e.num * e.price);
      });
      return sz.toFixed(2);
    },
  },
  components: {},
  data() {
    return {
      // 验证
      rules,
      // 列表数据
      monitorForm: {
        form: {
          type: 1,
          remark: "",
        },
        list: [],
      },
      // 商品搜索
      formsp: {
        name: [],
        girard: null,
        num: "",
        value: "",
      },
      inventory_num: "",
      price: "",
      show: true,
      // 监听滚动
      searchBarFixed: false,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  created() {
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 300
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 商品搜索
    querySearchAsync(queryString, cb) {
      if (queryString.trim() == "") {
        cb([]);
        return;
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { name: queryString.trim() })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { name: queryString.trim() }
      );
      goods_getGoodsSpu(data).then((res) => {
        if (res.errcode == 0) {
          res.data.goods.map((e) => {
            e.name = e.goods.name + "【" + e.spu_unit.title + "】";
          });
          var results = res.data.goods;
          if (this.$refs.searchSelect) {
            this.$refs.searchSelect.activated = true;
          }
          cb(results);
        } else {
          this.$message.error(res.errmsg);
          cb([]);
        }
      });
    },
    // 商品选择
    handleSelect(item) {
      this.formsp.name = item;
      this.formsp.girard = item.id;
      this.reportedSpills_checkGoods();
    },
    reportedSpills_checkGoods() {
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                goods_id: formsp.name.goods_id,
                goods_spu_id: formsp.girard,
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          goods_id: formsp.name.goods_id,
          goods_spu_id: formsp.girard,
        }
      );
      reportedSpills_checkGoods(data).then((res) => {
        if (res.errcode == 0) {
          this.inventory_num = res.data.num;
          this.price = res.data.price;
          setTimeout(() => {
            this.$refs.focusw2.focus();
          }, 100);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 商品选择确认(回车)
    mainor_sp(e) {
      var keyCode = window.event ? e.keyCode : e.which;
      if (keyCode == 13) {
        this.mainor_qr();
      }
    },
    // 点击添加
    mainor_qr() {
      let formsp = JSON.parse(JSON.stringify(this.formsp));
      if (!formsp.name.name) {
        this.$message.error("请填写商品名称");
        this.$refs.searchSelect.focus();
        return;
      } else if (formsp.num == "") {
        this.$message.error("请填写数量");
        this.$refs.focusw2.focus();
        return;
      } else {
        let monitorForm_list = JSON.parse(
          JSON.stringify(this.monitorForm.list)
        );
        let ind = 0;
        if (monitorForm_list.length != 0) {
          monitorForm_list.map((e, index) => {
            if (e.goods_spu_id == formsp.girard) {
              ind = e.goods_spu_id;
              return;
            }
          });
          if (ind == 0) {
            this.handle(formsp);
          } else {
            setTimeout(() => {
              this.$refs["num" + ind].focus();
              this.reset();
              ind = 0;
            }, 100);
          }
        } else {
          this.handle(formsp);
        }
      }
    },
    handle(formsp) {
      let list = JSON.parse(JSON.stringify(shuju.list));
      list.name = formsp.name.goods.name;
      list.goods_id = formsp.name.goods_id;
      list.goods_spu_id = formsp.name.id;
      list.spu_name = formsp.name.spu_name.title;
      list.unit = formsp.name.spu_unit.title;
      list.price = this.price;
      list.inventory_num = this.inventory_num;
      list.num = formsp.num;
      list.remark = formsp.name.remark;
      this.monitorForm.list.push(list);
      this.reset();
      setTimeout(() => {
        this.$refs.searchSelect.focus();
      }, 100);
    },
    reset() {
      this.formsp = JSON.parse(JSON.stringify(shuju.formsp));
      this.show = false;
      this.$nextTick(() => {
        this.show = true;
      });
    },
    // 删除
    scdelete(index) {
      this.monitorForm.list.splice(index, 1);
    },
    // 保存
    preservation() {
      this.$refs["userListFrom"].validate((valid) => {
        if (valid) {
          if (this.monitorForm.list.length == 0) {
            this.$message.error("请至少添加一个商品");
            return;
          }

          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            this.order_data().form,
            { list: JSON.stringify(this.order_data().list) }
          );
          reportedSpills_add(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.$router.go(-1);
            }else {
              this.$message.error(res.errmsg);
            }
          });
        }
      });
    },
    order_data() {
      let form = JSON.parse(
        JSON.stringify(this.monitorForm.form)
      );
      let sz = JSON.parse(JSON.stringify(this.monitorForm.list));
      let list = sz.map((e) => {
        let { name,spu_name,unit,show,inventory_num, ...sz } = e;
        return { ...sz };
      });
      return { form, list };
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.main_name {
  top: 5px;
  position: relative;
}
.main_addr {
  top: -5px;
  position: relative;
}
.mainor {
  /deep/.el-button--default {
    border-color: $menuActiveText;
    color: $menuActiveText;
  }
  /deep/.el-form {
    margin-top: 10px;
    /deep/.el-form-item--mini.el-form-item,
    /deep/.el-form-item--small.el-form-item {
      margin-bottom: 10px;
    }
  }
  .remark_in {
    width: 100%;
    /deep/.el-form-item__content {
      width: 80%;
      .el-input {
        width: 66.9%;
      }
    }
  }
  .mainor_sp {
    ul {
      margin-right: 20px;
      li {
        margin-bottom: 10px;
        & > span {
          display: inline-block;
          line-height: 32px;
          width: 60px;
          color: $colour_18;
          font-size: $font_14;
          text-align: right;
          em {
            color: $colour_red;
            margin-right: 5px;
          }
        }
        &:first-child {
          & > span {
            width: 85px;
          }
        }
      }
    }
  }
  .newConBox.on {
    width: calc(100% - 230px);
    padding-left: 0;
  }
  .mainor_pr {
    margin-left: 10px;
    margin-bottom: 10px;
    /deep/.el-button--default {
      border-color: $subActive;
      color: $menuText;
      &:hover {
        border-color: $menuActiveText;
        color: $menuActiveText;
      }
    }
    .mainor_prr {
      font-size: $font_16;
      color: $colour_18;
      span {
        color: #fe3b3b;
        margin-left: 10px;
      }
    }
  }
  .main_table {
    /deep/.el-table--small td {
      padding: 10px 0;
    }
  }
  .main_taf {
    /deep/.el-table--small td {
      padding-top: 0;
    }
    /deep/.el-form-item--small.el-form-item {
      margin-bottom: 16px;
      margin-top: 16px;
      margin-right: 0;
    }
  }
}
</style>
